package com.lagou.socket;

import com.lagou.Mapper;
import com.lagou.server.MinicatEngine;
import com.lagou.server.RequestProcessor;
import com.lagou.thread.HttpThreadPool;
import org.apache.commons.io.IOUtils;

import java.net.ServerSocket;
import java.net.Socket;

public class BioService implements MiniCatService {

    private ServerSocket serverSocket;
    private volatile boolean run = true;

    @Override
    public void listen(int port, int timeout) throws Exception {
        this.serverSocket = new ServerSocket(port);
        this.serverSocket.setSoTimeout(timeout);
    }

    @Override
    public void execute() throws Exception {
        MinicatEngine engine = new MinicatEngine();
        Mapper mapper = engine.loadServer();
        while (run) {
            try {
                Socket socket = serverSocket.accept();
                RequestProcessor processor = new RequestProcessor(socket, mapper);
                HttpThreadPool.build().execute(processor);
            } finally {
                //donothing
            }
        }
    }

    @Override
    public void shutdown() throws Exception {
        this.run = false;
        IOUtils.closeQuietly(serverSocket);
    }
}
